import { MessageType } from '@/config';

export async function setProxyDirect() {
  await browser.runtime.sendMessage({
    type: MessageType.setProxy,
    data: {
      value: {
        mode: 'direct',
      },
      scope: 'regular',
    },
  });
}

export interface SetProxyFixedServersOptions {
  scheme: string;
  host: string;
  port: number;
}

export async function setProxyFixedServers(options: SetProxyFixedServersOptions) {
  await browser.runtime.sendMessage({
    type: MessageType.setProxy,
    data: {
      value: {
        mode: 'fixed_servers',
        rules: {
          singleProxy: {
            scheme: options.scheme,
            host: options.host,
            port: options.port,
          },
        },
      },
      scope: 'regular',
    },
  });
}

export interface setProxyPACOptions {
  host: string;
  port: number;
}

export async function setProxyPAC(options: setProxyPACOptions, originList: string[]) {
  await browser.runtime.sendMessage({
    type: MessageType.setProxy,
    data: {
      value: {
        mode: 'pac_script',
        pacScript: {
          data:
            'function FindProxyForURL(url, host) {\n' +
            // 将数组转换为字符串格式注入
            `  if (${JSON.stringify(originList)}.includes(host))\n` +
            `    return 'PROXY ${options.host}:${options.port}';\n` +
            "  return 'DIRECT';\n" +
            '}',
        },
      },
      scope: 'regular',
    },
  });
}

export function getProxyUrls(proxyList: string) {
  const proxyUrls = proxyList
    .split('\n')
    .map((url) => {
      return url.trim();
    })
    .filter((url) => {
      // 过滤掉空行
      return url !== '';
    });

  return proxyUrls;
}
